// 引入类
let Player = require("../modules/Player");
let Game = require("../modules/Game");
let Judge = require("../modules/Judge");
let Event = require("../modules/Event");
let Score = require("../modules/Score");
let Log = require("../modules/Log");

var ObjectID = require("mongodb").ObjectID;
// 处理表单提交
var formidable = require("formidable");
// 引入自定义工具
var zty = require('../public/js/zty');
var excel2json = zty.excel2json;
var resbody = zty.resbody;


// 查找某类所有数据
let findall = Class => {
  return new Promise((resolve, reject) => {
    Class.find({}, (err, result) => {
      if (err) reject(err);
      resolve(result);
    })
  })
};

// 处理初赛赛人员安排
let arrangeGame0 = gameInfo => {
  return new Promise((resolve, reject) => {
    // 分组人数
    let num = gameInfo.groupNum;
    // 比赛性别
    let gameSex = gameInfo.gameSex;
    // 运动项目编号
    let eventId = gameInfo.eventId;
    // 分组结果
    let arrangeGroup = [];
    Player.find(
      {$or : [
          {playerSex: gameSex, trackEvent: eventId},
          {playerSex: gameSex, fieldEvent: eventId}
        ]
      }, (err, result) => {
        let allNum = result.length;
        // 分组数目
        let groupCount = Math.ceil(allNum / num);
        // 保存分组信息
        for (let i = 0; i < groupCount; i++) {
          arrangeGroup[i] = result.splice(0, num)
        }

        let newArrange = {
          gameInfo: gameInfo,
          // arrangeId: "a" + new Date().getTime(),
          arrangeGroup: arrangeGroup
        };

        resolve(newArrange);
      })
  });
};

// 处理决赛人员安排
let arrangeGame1 = gameInfo => {

  let newArrange = {
    gameInfo: gameInfo,
    // arrangeId: "a" + new Date().getTime(),
    arrangeGroup: [gameInfo.group]
  };

  return newArrange;
};


// 提供比赛安排列表
let arrangeList = async () => {
    let games = await findall(Game);

    let arrangeList = [];

    for (let i = 0,len = games.length; i < len; i++) {
      let newArrange;
      // 只处理初赛
      if (["0", "3"].includes(games[i].gameStatus)) {
        newArrange = await arrangeGame0(games[i]);
        arrangeList.push(newArrange);
      } else if (["1", "4"].includes(games[i].gameStatus)) {
        newArrange = await arrangeGame1(games[i]);
        arrangeList.push(newArrange);
      }
    }

    return arrangeList;
};


// 提供xx列表
exports.list = async function(req, res, next) {
  let newResbody = resbody(req);
  let target = req.params["target"];
  let data = null;
  switch (target) {
    case "event":
      data = await findall(Event);
      break;
    case "game":
      data = await findall(Game);
      break;
    case "judge":
      data = await findall(Judge);
      break;
    case "player":
      data = await findall(Player);
      break;
    case "arrange":
      data = await arrangeList();
      break;
    case "score":
      data = await findall(Score);
      break;
  }
  newResbody.status = 200;
  newResbody.msg = '获取' + target + '列表成功！';
  newResbody.data = data;
  Log.create(newResbody);
  res.json(newResbody);
};









